package main

import (
	"github.com/gorilla/websocket"
	"html3/internal/container"
	service2 "html3/internal/service"
	"html3/internal/tools"
	"log"
	"net/http"
)

// 定义全局变量，用于管理客户端连接和用户组
var (
	upgrader = websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
)

// 向单个用户推送消息
func pushMessageUser(w http.ResponseWriter, r *http.Request,
	sc *container.ServiceContainer) {
	message := r.URL.Query().Get("message")
	userId := r.URL.Query().Get("userId")
	sc.UserId = userId
	sc.Message = message
	// 调用服务层方法，向指定用户推送消息
	err := service2.SendMessageToClients(sc)
	if err != nil {
		w.Write([]byte("发送失败"))
		return
	}
	w.WriteHeader(http.StatusOK)
	w.Write([]byte("发送成功"))
}

// 向用户组推送消息
func pushMessageGroup(w http.ResponseWriter, r *http.Request,
	sc *container.ServiceContainer) {
	message := r.URL.Query().Get("message")
	groupName := r.URL.Query().Get("groupName")
	sc.GroupName = groupName
	sc.Message = message
	// 调用服务层方法，向指定用户组推送消息
	err := service2.SendMessageGroup(sc)
	if err != nil {
		w.Write([]byte("组发送失败"))
		return
	}
	w.WriteHeader(http.StatusOK)
	w.Write([]byte("组发送成功"))
}

// 处理WebSocket连接升级和消息收发
func handleConnections(w http.ResponseWriter, r *http.Request,
	sc *container.ServiceContainer) {
	// 将HTTP连接升级为WebSocket连接
	ws, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Println("upgrade:", err)
		return
	}
	clientId := genClientId()
	// 将WebSocket连接添加到客户端管理器中
	sc.ClientId = clientId
	_ = sc.Clients.Set(clientId, ws)
	go func() {
		defer func() {
			// 释放资源
			if err := ws.Close(); err != nil {
				log.Println("close:", err)
			}
			// 连接关闭时，从管理器中移除客户端
			_ = service2.DeleteWs(sc)
			_ = service2.DeleteClientFromGroupsByClientId(clientId, sc.GroupClients)
			_ = sc.Clients.Del(clientId)

		}()
		// 向客户端发送其客户端ID
		if err := ws.WriteMessage(websocket.TextMessage, []byte(clientId)); err != nil {
			log.Println("write:", err)
		}
		// 循环读取并处理WebSocket消息
		for {
			_, message, err := ws.ReadMessage()
			if err != nil {
				log.Println("read:", err)
				break
			}
			log.Printf("Received message: %s", message)
		}
	}()

	//fmt.Println("Number of goroutines:", runtime.NumGoroutine())
}

// 将客户端绑定到用户
func bindUser(w http.ResponseWriter, r *http.Request,
	sc *container.ServiceContainer) {
	userId := r.URL.Query().Get("userId")
	clientId := r.URL.Query().Get("clientId")
	// 从客户端管理器中获取连接
	conn, err := sc.Clients.Get(clientId)
	if err != nil {
		log.Printf("bindUser(w http.ResponseWriter, r *http.Request)  failed ")
		w.Write([]byte("绑定失败1"))
		return
	}
	sc.UserId = userId
	sc.ClientId = clientId
	sc.Conn = conn
	// 调用服务层方法，完成客户端和用户的绑定
	err = service2.Bind(sc)
	if err != nil {
		w.Write([]byte("绑定失败2"))
		return
	}
	w.Write([]byte("绑定成功"))
}

// 将客户端绑定到用户组
func bindGroup(w http.ResponseWriter, r *http.Request,
	sc *container.ServiceContainer) {
	groupName := r.URL.Query().Get("groupName")
	clientId := r.URL.Query().Get("clientId")
	sc.GroupName = groupName
	sc.ClientId = clientId
	// 调用服务层方法，完成客户端和用户组的绑定
	if err := service2.BindGroups(sc); err != nil {
		w.Write([]byte("绑定到组失败"))
		return
	}
	w.Write([]byte("绑定到组成功"))
}

// 生成随机客户端ID
func genClientId() string {
	return tools.RandStringBytes(32)
}

func authenticate(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// 在这里添加认证逻辑，例如检查Token或Basic Auth
		// 如果验证失败，可以返回401状态码
		if !isValid(r) {
			w.WriteHeader(http.StatusUnauthorized)
			return
		}
		next.ServeHTTP(w, r)
	})
}

func isValid(r *http.Request) bool {
	// 实现具体的验证逻辑
	// 例如从Header中获取Token并验证
	return true
}

// 主函数，启动HTTP服务器和WebSocket处理程序
func main() {
	sc := container.NewServiceContainer()
	http.Handle("/ws", authenticate(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		handleConnections(w, r, sc)
	})))
	http.HandleFunc("/push", func(w http.ResponseWriter, r *http.Request) {
		pushMessageUser(w, r, sc)
	})
	http.HandleFunc("/push-group", func(w http.ResponseWriter, r *http.Request) {
		pushMessageGroup(w, r, sc)
	})
	http.HandleFunc("/bind-user", func(w http.ResponseWriter, r *http.Request) {
		bindUser(w, r, sc)
	})
	http.HandleFunc("/bind-group", func(w http.ResponseWriter, r *http.Request) {
		bindGroup(w, r, sc)
	})
	//go func() {
	//	log.Println(http.ListenAndServe("localhost:6060", nil))
	//}()
	log.Println("Starting server on :8080")
	log.Fatal(http.ListenAndServe(":8080", nil))
}
